<!-- 竞赛-参赛者风采 -->
<template>
	<view class="container">
		<!-- 表单区域 -->
		<view class="form-container">
			<u-form :model="form" ref="form">
				<!-- 2寸照片 -->
				<view class="form-section">
					<view class="section-title">
						<text>头像</text>
						<text class="section-subtitle">使用真实头像更容易获得关注</text>
					</view>
					<!-- 			 @on-list-change="onchange"   -->
					<u-upload 
					   ref = "upload"
					   action="#" 
						 :file-list="photoList" 
						 @on-list-change="onchange"
						 @on-remove="(e) => deletePic(e, index)"  
						 :multiple="false"
						 max-count="1" 
						 upload-text="上传头像" 
						 :custom-btn="true"
						 :auto-upload="false"
						 width="99px"
						 height="99px"
						 :show-progress="false"
						 >
						<!-- 自定义上传图片 -->
						<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
							<u-icon name="camera" size="60" :color="$u.color['lightColor']"></u-icon>
						</view>
					</u-upload>
				</view>

				<!-- 姓名 -->
				<view class="form-section">
					<u-form-item label="姓名" prop="name" label-width="240">
						<u-input v-model="form.username" placeholder="请输入姓名" clearable />
					</u-form-item>
				</view>
				
				<!-- 参赛口号 -->
				<view class="form-section">
					<u-form-item label="参赛口号" prop="name" label-width="240">
						<u-input v-model="form.userkh" placeholder="请输入参赛口号" clearable />
					</u-form-item>
				</view>

				<!-- 个人简介 -->
				<view class="form-jianjie">
					<view class="" style="font-size: 16px;">
						<text>个人简介</text>
					</view>
					<view class="form-content" style="border: 1px solid #d8d8d8; margin-top: 20px;">
						<u-input type="textarea" height="350" v-model="form.userjianjie" placeholder="请输入个人简介" clearable />
					</view>
				</view>

				<!-- 2寸照片 -->
				<view class="form-section">
					<view class="section-title">
						<text>上传视频</text>
						<text class="section-subtitle">上传视频展示风采</text>
					</view>
<!-- 					<u-upload 
					   ref = "upload"
					   action="#" 
						 :file-list="videoList" 
						 @on-list-change="videoOnChange"  
						 @on-remove="(e) => deleteVideo(e, index)"  
						 :multiple="false"
						 max-count="1" 
						 upload-text="上传视频" 
						 :extension="['mp4','mov','m4v']"
						 :custom-btn="true"
						 :auto-upload="false"
						 width="120px"
						 height="120px"
						 :show-progress="false"
						 > -->
						<!-- 自定义上传图片 -->
		<!-- 				<view slot="addBtn" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
							<u-icon name="camera" size="60" :color="$u.color['lightColor']"></u-icon>
						</view>
					</u-upload> -->
					<!-- 视频上传 -->
					  <view class="video-container">
					    <u-button v-show="!videoList" @click="chooseVideo" type="primary">选择视频</u-button>					    
					    <view v-if="videoList" class="video-preview">
					      <video :src="videoList" controls class="video"></video>
								<!-- <video :src="videoInfo.path" controls class="video"></video> -->
	<!-- 				      <view class="video-info">
					        <text>文件名: {{ videoInfo.name }}</text>
					        <text>大小: {{ formatFileSize(videoInfo.size) }}</text>
					      </view> -->
					    </view>
					    
				<!-- 	    <view v-if="videoInfo.path" class="upload-btn">
					      <u-button @click="uploadVideo" :loading="uploading" type="success">
					        {{ uploading ? '上传中...' : '上传视频' }}
					      </u-button>
					    </view> -->
					    
					<!--    <u-toast ref="uToast"></u-toast>
					    <u-modal v-model="showProgress" :show-cancel-button="false" :show-confirm-button="false">
					      <view class="progress-content">
					        <u-loading mode="circle" size="40"></u-loading>
					        <view class="progress-text">上传进度: {{ uploadProgress }}%</view>
					      </view>
					    </u-modal> -->
					  </view>
				</view>


				<!-- 按钮组 -->
				<view class="button-group">
					<!-- 					<u-button type="default" @click="handlePrev" shape="circle" :custom-style="customStyleObject">
						上一步
					</u-button> -->
					<u-button type="primary" @click="handleNext" :custom-style="btuStyle" shape="circle" :loading="loading">
						保存
					</u-button>
				</view>
			</u-form>
		</view>
	</view>
</template>

<script>
	import util from '@/utils/util.js'
	export default {
		data() {
			return {
				//按钮统一色彩
				btuStyle: {
					"backgroundColor": "#03B8CD",
					"color": "#ffffff",
					marginRight: '20rpx',
				},

				loading: false,
				//图片上传地址
				action: '#',
				// 图片数组-头像照片
				base64Data :'', //存储base64	
				form: {
					username: '', ///姓名
					userkh: '', ///口号
					userjianjie: '', ///个人简介
					userfenban: '', ///分班
					userislock: ''
				},
				photoList: [], //保存图片URL
				photoListCode:'', ////保存图片CODE
				videoList:'', ///保存视频
				videoListCode: '', ///保存视频CODE		
				// 按钮组中的样式写法
				customStyleObject: {
					marginRight: '20rpx',

				},	
				// 视频上传
				videoInfo: {
					path: '',
					name: '',
					size: 0
				},
				// videoInfo: {
				// 	"restype": "10",  //#资源类型，10,视频，11文档，12普通文件
				// 	"resfile": ''  //file --文件,
				// },
				uploading: false,
				uploadProgress: 0,
				showProgress: false,
				isEdit: false,
				jscode: ''
				
			}
		},
		onLoad(options) {
			this.jscode = options.jscode
		},
		onShow() {
			if(!this.isEdit) {
				this.selectBjsUserInfo()
			} else {
				this.isEdit = false
			}
		  
		},
		methods: {
			// 获取竞赛用户信息
			selectBjsUserInfo() {
				// 打开个人信息
				this.$u.api.querybjsuserbycode({
					"usercode": uni.getStorageSync('usercode'),
				}).then(res => {
					let base_info = res.data.base_info;
					console.log('jsb-user：', res,base_info);
					// 方法2：合并更新
					this.form = {}					
					this.form = {
							username: base_info.user_name, ///姓名
							userkh: base_info.user_cskh, ///口号
							userjianjie: base_info.user_desc, //简介
							userfenban: base_info.user_fenban, //分班
							userislock: base_info.user_islock, //文化程度							
					}
					console.log('video-1：', this.form);
					this.photoListCode= base_info.user_header_uri && base_info.user_header_uri.length > 0 ? base_info.user_header_uri[0].imguri : null,
					this.videoListCode= base_info.user_video_uri && base_info.user_video_uri.length > 0 ? base_info.user_video_uri[0].imguri : null,
					this.videoList=  base_info.user_video_uri && base_info.user_video_uri.length > 0 ? base_info.user_video_uri[0].url : null,					
					this.photoList = []
					
					this.photoList.push({
						url: base_info.user_header_uri && base_info.user_header_uri.length > 0 ? base_info.user_header_uri[0].url : null
					})
					console.log('jsb-user-1：', base_info.user_header_uri.length,this.photoList);
				})
				
				
			},
			// 删除图片
			deletePic(event,index) {
			  this.photoList.splice(event, 1)
				console.log('删除:',this.form)
			},
			
			// 图片添加到list中触发
			onchange(list, name) {
				this.isEdit = true
				if(this.photoList.length == 0) {
					if(list.length != 0){
						const file = list[0]
						console.log("onchange:", file.url)
						// 处理新准备上传的照片文件（添加必要字段）
						const newFiles = list.map(item => ({
							url: item.url, // 临时路径
						}))
						this.photoList = []
						this.photoList = [...this.photoList, ...newFiles];									
				
						// 将图片转换为Base64
						util.getPhotoBase64(file.url, base64 => {
							// console.log('main-bser64', base64)
							this.base64Data = base64
							// 转换成功后上传
							this.uploadBase64()
						})	
							
					}
	    }
	     console.log("onchange-3:", this.form)	
			},

			// 上传Base64数据到服务器
			uploadBase64() {
				// console.log('upload:', this.base64Data)
				if (!this.base64Data) {
					uni.showToast({
						title: '请先选择图片',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '上传中...'
				})
				// 调用照片上传接口
				this.$u.api.uploadres({
					"usercode": uni.getStorageSync('usercode'),
					"rescode": this.base64Data,
					"restype": "0",
					"resdesc": "上传个人头像照片"
				}).then(res => {
					// 保存服务端返回的图片id
					this.photoListCode = res.data.base_info
					console.log('uploadres:', res,this.photoListCode)
				})
			},
			
			
			// 视频上传
	    // 选择视频
			chooseVideo() {
				uni.chooseVideo({
					sourceType: ['album', 'camera'],
					compressed: true,
					maxDuration: 60,
					success: (res) => {
						console.log('视频上传',res)
						this.videoInfo = {
							path: res.tempFilePath,
							name: this.getFileName(res.tempFilePath),
							size: res.size
						};						
						util.getPhotoBase64(res.tempFilePath, base64 => {
							// console.log('main-viedeo-bser64', base64)
							this.base64Data = base64
							// 转换成功后上传
							this.videouploadBase64()
						})	
					},
					fail: (err) => {
						this.$refs.uToast.show({
							title: '选择视频失败',
							type: 'error'
						});
					}
				});
			},
			
			
			// video上传base64位视频到服务端
			videouploadBase64() {
				// console.log('upload:', this.base64Data)
				if (!this.base64Data) {
					uni.showToast({
						title: '请先选择视频',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '上传中...'
				})
				// 调用照片上传接口
				this.$u.api.uploadres({
					"usercode": uni.getStorageSync('usercode'),
					"rescode": this.base64Data,
					"restype": "0",
					"resdesc": "上传个人风采视频"
				}).then(res => {
					// 保存服务端返回的图片id
					this.videoListCode = res.data.base_info
					console.log('uploadres-video:',res, this.videoListCode)
				})
			},
			
			
			
			
			// 上传视频到指定接口
			uploadVideo() {
				if (!this.videoInfo.resfile) {
					this.$refs.uToast.show({
						title: '请先选择视频',
						type: 'warning'
					});
					return;
				}
				
				this.uploading = true;
				this.showProgress = true;
				this.uploadProgress = 0;
				
				// let formData = new FormData();
			 //  // 文件形式上传
				// formData.append('restype', '10'); // 资源类型：10=视频
				// formData.append('resfile', this.videoInfo.path);
				
				this.$u.api.fileuploadres(this.videoInfo,{
					headers:{
						'Content-Type': 'multipart/form-data' // 必须设置
					},
				}).then(res => {
					 console.log('上传视频：', res)
				})
				
				// 创建上传任务
				// const uploadTask = uni.uploadFile({
				// 	url: 'https://your-domain.com/api/common/uploadres', // 替换为实际接口地址
				// 	filePath: this.videoInfo.path,
				// 	name: 'resfile',
				// 	formData: {
				// 		restype: '10' // 资源类型，10表示视频
				// 	},
				// 	success: (uploadRes) => {
				// 		const data = JSON.parse(uploadRes.data);
				// 		if (data.code === 200) {
				// 			this.$refs.uToast.show({
				// 				title: '上传成功',
				// 				type: 'success'
				// 			});
				// 			// 上传成功后的处理，如返回文件路径或ID
				// 			console.log('上传成功:', data.data);
				// 		} else {
				// 			this.$refs.uToast.show({
				// 				title: data.msg || '上传失败',
				// 				type: 'error'
				// 			});
				// 		}
				// 	},
				// 	fail: (err) => {
				// 		this.$refs.uToast.show({
				// 			title: '上传失败: ' + err.errMsg,
				// 			type: 'error'
				// 		});
				// 	},
				// 	complete: () => {
				// 		this.uploading = false;
				// 		this.showProgress = false;
				// 	}
				// });
				
				// 监听上传进度
				// uploadTask.onProgressUpdate((res) => {
				// 	this.uploadProgress = res.progress;
				// });
			},
			
			// 获取文件名
			getFileName(path) {
				return path.substring(path.lastIndexOf('/') + 1);
			},
			
			// 格式化文件大小
			formatFileSize(size) {
				if (size < 1024) {
					return size + ' B';
				} else if (size < 1024 * 1024) {
					return (size / 1024).toFixed(2) + ' KB';
				} else {
					return (size / (1024 * 1024)).toFixed(2) + ' MB';
				}
			},
	
			// 视频上传结束	

			// 保存后
			handleNext() {
				console.log('save:',this.form, this.photoListCode,this.videoListCode)
				this.$u.api.updatebjsuser({
					"usercode": uni.getStorageSync('usercode'), //#选手用户code
					"username": this.form.username,//#选手名称
					"userheaderuri": this.photoListCode,//#选手头像
					"userfenban": this.form.userfenban,//#选手分班名称
					"usercskh":this.form.userkh,//#参数口号
					"userdesc": this.form.userjianjie,//#个人简介
					"uservideouri": this.videoListCode,//#个人风采视频
					"userislock": this.form.userislock//#选手是否锁定，锁定后不允许修改信息
				}).then(res => {
					console.log('save：', res)
					uni.redirectTo({
						url: `/pages/Practitioner/prizeFight/competitor?jscode=${this.jscode}`
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 10rpx;
		// background-color: #f5f5f5;
		min-height: 100vh;


		.slot-btn {
			width: 104px;
			height: 104px;
			display: flex;
			justify-content: center;
			align-items: center;
			background: rgb(244, 245, 246);
			border-radius: 10rpx;
			margin-left: 10px;
		}

		.slot-btn__hover {
			background-color: rgb(235, 236, 238);
		}

		.header {
			margin-bottom: 40rpx;

			.title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}
		}

		/deep/ .u-steps {
			background: #fff;
			padding: 30rpx;
			border-radius: 12rpx;
			margin-bottom: 30rpx;
		}

		.form-container {
			background: #fff;
			padding: 40rpx;
			border-radius: 12rpx;

			.form-section {
				margin-bottom: 40rpx;
				display: flex;
				justify-content: space-between;
				flex-direction: row;
				align-content: flex-start;
				align-items: center;


				.section-title {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 16rpx;

					.required {
						color: #f56c6c;
						margin-right: 8rpx;
					}
				}

				.section-subtitle {
					font-size: 26rpx;
					color: #999;
					margin-bottom: 20rpx;
					display: block;
				}
			}

			/deep/ .u-form-item__label {
				.required {
					color: #f56c6c;
					margin-right: 8rpx;
				}
			}

			.button-group {
				display: flex;
				justify-content: space-between;
				margin-top: 60rpx;

				// 此样式主要为了适配wx小程序的按钮
				/deep/ .u-size-default {
					width: 350px;
				}

				.u-btn {
					flex: 1;
				}
			}
		}
		
		// 视频
		.video-preview {
		  margin-top: 30rpx;
		}
		
		.video {
		  width: 300rpx;
		  height: 300rpx;
		  border-radius: 10rpx;
		}
		
		.video-info {
		  margin-top: 20rpx;
		  display: flex;
		  flex-direction: column;
		}
		
		.video-info text {
		  margin-bottom: 10rpx;
		  font-size: 28rpx;
		  color: #606266;
		}
		
		.upload-btn {
		  margin-top: 40rpx;
		}
		
		.progress-content {
		  padding: 40rpx;
		  display: flex;
		  flex-direction: column;
		  align-items: center;
		  justify-content: center;
		}
		
		.progress-text {
		  margin-top: 20rpx;
		  font-size: 28rpx;
		  color: #606266;
		}
	}
</style>